#include <Network.h>
#include <string>




Network::Network(Telemetry *t, Video *v) : QThread()
{
	telemetry = t;
	video = v;
	record = 0;
}


void Network::run()
{

	fd_set readfs;
	int maxSock, err;
	struct timeval tv;
	unsigned char buff[230400];
		
	int recv;
		
	recv = 0;		

	udp_server_t serv_gps;

	img_receiver_t img_recv = open_img_receiver(5000, init_size(320,240), IMG_RGB24);

	init_server(&serv_gps, 5001);

	gga_t gga;

	while(1)
	{
		
		maxSock = 0;
		    
		FD_ZERO (&readfs);    
		FD_SET (img_recv.serv.s_ecoute, &readfs);
		FD_SET (serv_gps.s_ecoute, &readfs);
		    
		maxSock = img_recv.serv.s_ecoute > maxSock ? 
		img_recv.serv.s_ecoute : maxSock;

		maxSock = serv_gps.s_ecoute > maxSock ? 
		serv_gps.s_ecoute : maxSock;	
	    
		tv.tv_sec = 2;
		tv.tv_usec = 0;
		    
		err = select (maxSock + 1, &readfs, NULL, NULL, &tv);
		    
		    switch (err)
		    {
		        case 0:
		            // timeout 
		            break;
		            
		        case -1:
		            // error 
		            break;
		            
		        default:				
		            if (FD_ISSET (img_recv.serv.s_ecoute, &readfs))
		            {
						recv_img(&img_recv);
						memcpy(buff, img_recv.imgs[img_recv.last_recv].data, 230400);
						emit set_img(buff, 320, 240);
						write_image2ppm(img_recv.imgs[img_recv.last_recv], "toto.ppm");

						if(record)
							add_frame2video_record(v,img_recv.imgs[img_recv.last_recv]);
		            }
					else if(FD_ISSET (serv_gps.s_ecoute, &readfs))
					{
						recv_gps_gga(&gga, &serv_gps);				
						telemetry->set_gps(QString(gga.latitude));
						
					}  
			}
		            
		
	}

}


void Network::record_video()
{
	v = open_video_record("video.avi", init_size(320,240), 6);
	record = 1;
	
}

void Network::stop_record()
{
	record = 0;
	close_video_record(v);
}

